package com.jonny.dbtools.utils;


import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

public final class ValidatorUtil {

    private static final Validator VALIDATOR =
            Validation.byDefaultProvider()
                    .configure()
                    .messageInterpolator(new ParameterMessageInterpolator())
                    .buildValidatorFactory()
                    .getValidator();


    public static <T> Map<String, Object> valid(T object) {

        Set<ConstraintViolation<T>> validate = VALIDATOR.validate(object);
        Map<String, Object> map = new HashMap<>();
        if (validate.isEmpty()) {
            map.put("flag", false);
            return map;
        }
        Stream.of(validate).forEach(action -> {
            StringBuilder sb = new StringBuilder();
            for (ConstraintViolation<T> orderConstraintViolation : action) {
                sb.append(orderConstraintViolation.getMessage());
                sb.append("\n");
            }
            map.put("flag", true);
            map.put("msg", sb.toString());
        });
        return map;
    }
}
